/*
 * map_lua.c
 */

#include "map_lua.h"
#include "map_creator.h"
#include <stdio.h>
#include <lua/luaR.h>

int map_lua_initialized = 0;

/*
 * Initializes the map Lua interface.
 */
int map_lua_initialize() {
    int status;
    if( !map_lua_initialized ) {
        luaR_package_create();
        luaR_package_add("createMap", map_lua_create);
        luaR_package_add("writeTile", map_lua_writeTile);
        luaR_package_add("mapExists", map_lua_exists);
        luaR_package_set("RG_map");

        luaR_load_file("scripts/map.lua");
        map_lua_initialized = 1;
        return 0;
    }
    else {
        /* TODO: warning message */
        return 1;
    }
}

/*
 * Takes the top entity on the stack of the given Lua state and attempts to
 * convert it into a map_tile structure.
 */
struct map_tile map_lua_getTile( lua_State *L ) {
    struct map_tile tile;
    int table_index;
    table_index = lua_gettop(L);
    lua_rawgeti(L, table_index, 1);
    lua_rawgeti(L, table_index, 2);
    tile.type = (unsigned char)lua_tonumber(L, table_index + 1);
    tile.altitude = (unsigned char)lua_tonumber(L, table_index + 2);
    lua_pop(L, 3);
    return tile;
}

/*
 * Lua hook to the function:
 * int create_map( const char *name, unsigned int height, unsigned int width );
 */
int map_lua_create( lua_State *L ) {
    const char *filename;
    unsigned int height;
    unsigned int width;
    if( lua_gettop(L) < 3 ) {
        lua_pushstring(L, "Too few arguments");
        lua_error(L);
    }
    else {
        filename = lua_tostring(L, 1);
        height = lua_tonumber(L, 2);
        width = lua_tonumber(L, 3);
        create_map(filename, height, width);
        return 0;
    }
    return 0;
}

/*
 * Lua hook to the function:
 * int write_tile( struct map_tile *t );
 */
int map_lua_writeTile( lua_State *L ) {
    struct map_tile tile;
    if( lua_gettop(L) != 1 ) {
        lua_pushstring(L, "Too few arguments");
        lua_error(L);
    }
    else {
        tile = map_lua_getTile(L);
        write_tile(&tile);
    }
    return 0;
}

/*
 * Lua hook to the function:
 * int map_exists( const char *name );
 */
int map_lua_exists( lua_State *L ) {
    const char *filename;
    if( lua_gettop(L) != 1 ) {
        lua_pushstring(L, "Too few arguments");
        lua_error(L);
        return 0;
    }
    else {
        filename = lua_tostring(L, 1);
        lua_pushboolean(L, map_exists(filename));
        return 1;
    }
}
